﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebBanThuoc.Function;
using WebBanThuoc.DTO;
using WebBanThuoc.Server;
using WebBanThuoc.DAO;

namespace WebBanThuoc.admin
{
    public partial class DangNhap : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (!IsPostBack)
            {
                
                if (Request.QueryString["func"] == "logout")
                {
                    if (FuncAdmin.IsLogin(Session))
                    {
                        UserAdmin au = FuncAdmin.getDataUserLoginCurrent(Session);
                        FuncAdmin.removeDataUserLoginAdminCurrent(Session, au.UserName, au.Code);
                    }
                }
                if (FuncAdmin.IsLogin(Session))
                {
                    ReURL();
                }
            }
            else
            {
                if (checkDefaultSubmit())
                {
                    Session.Add("cleanFrom", true);
                }
                else
                {
                    if (Request.Params["btn_DangNhap"] != null)
                    {
                        Login();
                    }
                }
            }
            
        }

        private bool checkDefaultSubmit()
        {
            if (Request.Params["btn_DangNhap"] != null)
            {
                return false;
            }
            return true;
        }


        private void Login()
        {
            string txt_User = Request.Params["txt_User"];
            string txt_Password = Request.Params["txt_Password"];

            IServerWeb sw = new ServerWeb();
            NhanVien_DAO daoNV = new NhanVien_DAO(sw.Connection);

            UserAdmin ua = daoNV.loginByKey(txt_User, txt_Password);

            if (ua != null)
            {
                FuncAdmin.createDataUserLoginAdminCurrent(Session, ua);
                ReURL();
            }
            else
            {
                Session.Add("loginFail", false);
            }
            sw.closeConnection();
        }

        private void ReURL()
        {
            string url = Session["URLCurrentActive_SendTo_Login"] as string;
            if (url != null && url.ToString().Trim() != "")
            {
                Session.Remove("URLCurrentActive_SendTo_Login");
                Response.Redirect(url);
            }
            else
            {
                Response.Redirect("/admin/home.aspx");
            }
        }

    }
}